<template>
  <!-- 后台主页布局 -->
  <div class="common-layout">
    <el-container>
      <el-header class="top">
        <div class="header-content">
          <span class="title">ERP项目工程</span>
          <div class="user-info">
            <span v-if="userInfo">{{ userInfo.uname }}</span>
            <el-button type="text" @click="handleLogout" style="color: white; margin-left: 10px;">
              退出
            </el-button>
          </div>
        </div>
      </el-header>
      <el-container>
        <el-aside width="240px" class="left">
          系统菜单

          <!--添加Menu菜单组件-->
          <el-menu
            class="el-menu-vertical-demo" @select="handlerSelect">
            <el-sub-menu v-for="menu in menus" :index="String(menu.id)">
              <template #title>
                <span>{{ menu.label }}</span>
              </template>
              <el-menu-item v-for="subMenu in menu.subMenus" :index="String(subMenu.id)">
                {{ subMenu.label }}
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        <el-main class="right">
          <!--通过点击左边菜单，动态显示不同组件 -->
          <component :is="currentComponent"></component>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { logout, getUserInfo } from '../utils/auth';
import { request } from '../utils/request';
import axios from 'axios';

import AddCustomer from './AddCustomer.vue';
import ListCustomer from './ListCustomer.vue';
import ListAfterSale from './ListAfterSale.vue';
import ListCustOrder from './ListCustOrder.vue';
import AddSellJh from './AddSellJh.vue';
import CustomerArea from './CustomerArea.vue';
import YearMonthCount from './YearMonthCount.vue';
import ListSellJh from './ListSellJh.vue';
import AddMenus from './AddMenus.vue';
import UserManager from './UserManager.vue';
import RolerManager from './RolerManager.vue';
import TreeDemo from './TreeDemo.vue';
import CategoryManager from './CategoryManager.vue';
import ItemManger from './ItemManger.vue';
import BuyListManager from './BuyListManager.vue';
import InStoreList from './InStoreList.vue';
import ListOutStore from './ListOutStore.vue';
import ListStore from './ListStore.vue';
import EmployeeCount from './EmployeeCount.vue';
import AfterSaleCount from './AfterSaleCount.vue';
import YearNumCount from './YearNumCount.vue';
import ListLog from './ListLog.vue';
import LogStats from './LogStats'
import LogUrlStats from './LogUrlStats'
import LogUnameStats from './LogUnameStats'


const router = useRouter();

//声明数组保存所有组件
const views = [
  AddCustomer,
  ListCustomer,
  ListAfterSale,
  ListCustOrder,
  AddSellJh,
  CustomerArea,
  YearMonthCount,
  ListSellJh,
  AddMenus,
  UserManager,
  RolerManager,
  TreeDemo,
  CategoryManager,
  ItemManger,
  BuyListManager,
  InStoreList,
  ListOutStore,
  ListStore,
  EmployeeCount,
  AfterSaleCount,
  YearNumCount,
  null,
  ListLog,
  LogStats,
  LogUrlStats,
  LogUnameStats
];

//声明变量保存当前需要显示的组件名
const currentComponent = ref(views[0]);
//声明菜单对象集合数据
const menus = ref([]);
//显示用户名
const userInfo = ref({ uname: '' });

onMounted(() => {
  const info = getUserInfo();
  if (info) {
    userInfo.value = info;
  }
}); 

// 处理登出
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    await request({
      url: "http://localhost:8081/logout",
      method: 'get',
    }).then((response)=>{
      console.log("logout:" +response);
      logout();
    }).catch((error)=>{
      console.log(error);
    });

    ElMessage.success('已退出登录');
     router.push('/'); // 这里跳转

  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('登出失败，请稍后再试');
    }
  }
};

/*menu组件选中叶子节点触发的函数，参数index：菜单节点的index值，对应数据库菜单节点的id*/
const handlerSelect = (id) => {
  console.log(id);
  //发生ajax请求，加载组件下标
  request({
    url: `http://localhost:8081/compIndex?id=${id}`,
    method: 'get'
  })
    .then((response) => {
      //动态该currentComponent赋值,从组件集合views中获取的组件名字
      currentComponent.value = views[response.data];
    })
    .catch((error) => {
      console.log(error);
    });
};

//页面加载，发生ajax请求加载左侧菜单信息和用户信息
onMounted(function(){
  console.log("onMounted listMenus");
request({
  url: "http://localhost:8081/listMenus",
  method: 'get',
})
      .then((response)=>{
        console.log(response);
        //将响应的数据绑定到menus，实现数据渲染
        menus.value=response.data;
      })
      .catch((error)=>{
        console.log(error);
      });
});
</script>

<style scoped>
.top {
  background-color: #007BFF; /* 主色调 */
  color: white;
  padding-top: 15px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
}

.left {
  background-color: #F8F9FA; /* 浅灰色背景 */
  height: 600px;
}
.right {
  background-color: #FFFFFF; /* 白色背景 */
}
.el-header, .el-aside, .el-main {
  padding: 10px;
}
</style>